/*
 * @Author: 薛严 348352046@qq.com
 * @Date: 2023-04-15 17:05:53
 * @LastEditors: 薛严 348352046@qq.com
 * @LastEditTime: 2023-04-15 17:26:01
 * @FilePath: /applet-server/WXBizDataCrypt.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const crypto = require("crypto-js");

function WXBizDataCrypt(appId, sessionKey) {
  this.appId = appId;
  this.sessionKey = sessionKey;
}

WXBizDataCrypt.prototype.decryptData = (e, i) => {
  const sessionKey = new Buffer(this.sessionKey, "base64");
  const encryptedData = new Buffer(e, "base64");
  const iv = new Buffer(i, "base64");
  try {
    const decipher = crypto.createDecipheriv("aes-128-cbc", sessionKey, iv);
    decipher.setAutoPadding(true);
    const decoded = decipher.update(encryptedData, "binary", "utf8");
    decoded += decipher.final("utf8");
    decoded = JSON.parse(decoded);
  } catch (error) {
    throw new Error("Illegal Buffer");
  }
  return  decoded
};

module.exports = WXBizDataCrypt